import { createTeris } from "./Teris";
import { TerisControl } from "./TerisControl";
import { GameStatus, GameViewer, MoveDirection } from "./types";
import { SquareGroup } from "./SquareGroup";
import GameConfig from "./GameConfig";
import { TerisRule } from "./TerisRule";

export class Game {
  // 游戏状态
  private _gameStates: GameStatus = GameStatus.init
  // 玩家当前操作的方块
  private _curTeris?: SquareGroup
  // 下一个方块
  private _nextTeris: SquareGroup = createTeris({x: 0, y: 0})
  // 计时器
  private _timer?: number
  // 自动下落的间隔时间
  private _duration: number = 1000

  constructor(private _viewer:GameViewer){
    this.resetCenterPoint(GameConfig.nextSize.width, this._nextTeris)
    this._viewer.showNext(this._nextTeris)
  }

  /**
   * 游戏开始
   */
  start(){
    // 更改游戏状态
    if(this._gameStates === GameStatus.playing) return

    this._gameStates = GameStatus.playing
    if(!this._curTeris){
      this.switchSquare()
    }
    this.autoDrop()
  }

  /**
   * 游戏暂停
   */
  pause(){
    // 更改游戏状态
    if(this._gameStates === GameStatus.playing) {
      this._gameStates = GameStatus.pause
      clearInterval(this._timer)
      this._timer = undefined
    }

  }

  control_left() {
    if(this._curTeris && this._gameStates === GameStatus.playing){
      TerisControl.move(this._curTeris, MoveDirection.left)
    }
  }

  control_right() {
    if(this._curTeris && this._gameStates === GameStatus.playing){
      TerisControl.move(this._curTeris, MoveDirection.right)
    }
  }

  control_down() {
    if(this._curTeris && this._gameStates === GameStatus.playing){
      TerisControl.move(this._curTeris, MoveDirection.down)
    }
  }

  control_rotate() {
    if(this._curTeris && this._gameStates === GameStatus.playing){
      TerisRule.rotate(this._curTeris)
    }
  }

  /**
   * 当前方块自由下落
   */
  private autoDrop() {
    if(this._timer || this._gameStates !== GameStatus.playing){
      return
    }
    this._timer = setInterval(() => {
      if(this._curTeris){
        TerisControl.move(this._curTeris, MoveDirection.down)
      }
    }, this._duration)
  }

  /**
   * 切换方块
   */
  private switchSquare(){
    this._curTeris = this._nextTeris
    this.resetCenterPoint(GameConfig.pannelSize.width, this._nextTeris)
    this._nextTeris = createTeris({x: 0, y: 0})
    this.resetCenterPoint(GameConfig.nextSize.width, this._nextTeris)
    this._viewer.switch(this._curTeris)
    this._viewer.showNext(this._nextTeris)
  }

  /**
   * 重新设置方块的中心点坐标，让方块出现在中上方
   * @param width 面板逻辑宽度
   */
  private resetCenterPoint(width: number, teris:SquareGroup){
    const x = Math.ceil(width) / 2 - 1
    let y = 0
    teris.centerPoint = { x, y}
    while(teris.squares.some(it => it.point.y <  0)){
      teris.squares.forEach(sq => {
        sq.point = {
          x: sq.point.x,
          y: sq.point.y + 1
        }
      })
    }
  }
}